package com.yeskery.boot.log.record.starter.core;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 日志上下文对象
 * @author dushuangjiang
 * @date 2021-11-11 17:31
 */
public class LogRecordContext {

    private static final InheritableThreadLocal<Stack<Map<String, Object>>> VARIABLE_MAP_STACK = new InheritableThreadLocal<>();

    /**
     * 获取当前的所有参数对象
     * @return 当前的所有参数对象
     */
    public static Map<String, Object> getVariables() {
        Stack<Map<String, Object>> stack = VARIABLE_MAP_STACK.get();
        if (stack == null) {
            return Collections.emptyMap();
        }
        return stack.peek();
    }

    /**
     * 获取指定的参数对象
     * @param name 参数名称
     * @param value 参数值
     */
    public static void putVariable(String name, Object value) {
        Stack<Map<String, Object>> stack = VARIABLE_MAP_STACK.get();
        if (stack != null) {
            stack.peek().put(name, value);
        }
    }

    /**
     * 为当前方法开启一个新的存储空间
     */
    public static void putEmptySpan() {
        Stack<Map<String, Object>> stack = VARIABLE_MAP_STACK.get();
        if (stack == null) {
            stack = new Stack<>();
            VARIABLE_MAP_STACK.set(stack);
        }
        stack.push(new LinkedHashMap<>());
    }

    /**
     * 清除当前方法的存储栈
     */
    public static void clear() {
        VARIABLE_MAP_STACK.get().pop();
    }
}
